'use strict';

const Service = require('egg').Service;
var moment = require('moment');

// const Sequelize = require('sequelize');

const {
    ERROR,
    SUCCESS,
} = require('../util/util');

class MessageService extends Service {
  async selectMessages(uid) {
      const { ctx, logger, app } = this

      try {

          const msg = await app.model.query('SELECT tid FROM messages WHERE ruid = :ruid GROUP BY tid', {
            replacements: { ruid: uid },
            type: app.model.QueryTypes.SELECT
          })

          let message = []
          for (var item of msg) {
            let coms = await app.model.query('SELECT msg.*,puser.uid AS puid,puser.avatarUrl AS pavatarUrl,puser.username AS pusername,ruser.uid AS puid,ruser.avatarUrl AS ravatarUrl,ruser.username AS rusername FROM messages AS msg LEFT JOIN users AS puser ON puser.uid=msg.puid LEFT JOIN users AS ruser ON ruser.uid=msg.ruid WHERE msg.tid=:tid AND msg.state=1 AND ruid=:ruid ORDER BY msg.created_at DESC LIMIT 1 OFFSET 0', {
              replacements: { tid: item["tid"] ,ruid: uid },
              type: app.model.QueryTypes.SELECT
            })
          
            if (coms[0].rcid/1 === -1) { // 当rcid===-1 的时候代表信息是直接发给楼主的
              let topic = await app.model.query('SELECT tops.*,puser.avatarUrl AS avatarUrl,puser.username AS username,cons.cityDesc AS cityDesc FROM topics AS tops LEFT JOIN users AS puser ON puser.uid=tops.uid LEFT JOIN configs AS cons ON cons.`code`=tops.cityType WHERE tid=:tid', {
                replacements: {tid: coms[0].tid},
                type: app.model.QueryTypes.SELECT
              })

              let con = await app.model.query('SELECT * FROM configs WHERE `code`=:code',{
                replacements: {code: topic[0].cityType}
              })

              topic[0].cityConfig = con[0][0]

              coms[0].topic = topic[0]
              coms[0].comment = {}
            }else {
              let comment = await app.model.query('SELECT coms.*,puser.avatarUrl AS avatarUrl,puser.username AS username FROM comments AS coms LEFT JOIN users AS puser ON puser.uid=coms.puid WHERE coms.id=:rid', {
                replacements: {rid: coms[0].rcid},
                type: app.model.QueryTypes.SELECT
              })
              coms[0].comment = comment[0]

              let topic = await app.model.query('SELECT * FROM topics WHERE tid=:tid', {
                replacements: {tid: coms[0].tid},
                type: app.model.QueryTypes.SELECT
              })

              let con = await app.model.query('SELECT * FROM configs WHERE `code`=:code',{
                replacements: {code: topic[0].cityType}
              })

              topic[0].cityConfig = con[0][0]

              coms[0].topic = topic[0]
            }

            message.push(coms[0])
          }

          return Object.assign(SUCCESS(), {
            data: Object.assign(message),
          });
      } catch (error) {
        logger.error(error)
        return Object.assign(ERROR(), {
            msg: '服务器错误',
        });
      }
  }

  async creatMessage(tid, puid, ruid, cid, rcid, content) {
    const { ctx, logger, app } = this

    try {
      const res = await ctx.model.Message.create({
        tid,
        puid,
        ruid,
        cid,
        rcid,
        content,
      })

      logger.info("消息插入成功" + JSON.stringify(Object.assign(res)))
    } catch (error) {
      logger.error(error)
    }
  }
}

module.exports = MessageService;
